package pdi.IO;


import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.collections4.iterators.ArrayIterator;

import pdi.core.Image;


import utils.MyUtils;

public class RawImgReader extends ImgReader {


	protected String dirPath;
	protected ArrayIterator<File> imgsIterator;

	public  RawImgReader(String dirPath) {
		this.dirPath = dirPath;		
	}

	@Override
	public void open() {
		//check if exist
		File dir = new File(dirPath);
		if(!dir.exists() || !dir.isDirectory())
			throw new IllegalArgumentException("There isn't a derectory on the requested path");

		File[] files = getAllImageFiles(dirPath);	
		this.imgsIterator = new ArrayIterator<File>(files);
	}

	@Override
	public void close() {
		this.imgsIterator.reset();
		this.imgsIterator = null;

	}

	@Override
	public Image readNext() {
		if(this.imgsIterator == null )
			throw new IllegalArgumentException("Directory without images, wrong directory or unopen reader");

		Image img = null;

		try {
			if(this.imgsIterator.hasNext()){
				File imgFile = this.imgsIterator.next();
				img = new Image(imgFile.getPath());
				
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}	

		return img;
	}

	@Override
	public List<Image> readAll() {
		open();
		
		//put the iterator in the begining
		this.imgsIterator.reset();

		//read all images and put in a list
		List<Image> ret = new ArrayList<Image>();
		Image img = null;
		while((img = readNext()) != null)		
			ret.add(img);

		close();
		
		return ret;
	}


}
